import React from "react";
import { useImmer } from "use-immer";

type Event = React.ChangeEvent<HTMLInputElement>;

const FormObj = () => {
	const [person, updatePerson] = useImmer({
		name: "Nick Stim",
		age: 18,
		artwork: {
			title: 'Blue Nana',
			city: 'Hamburg',
			image: 'https://i.imgur.com/Sd1AgUOm.jpg',
		}
	});

	const handleChange = (e: Event) => {
		const { name, value } = e.target;
		updatePerson(draft => {
			const [parentKey, childKey] = name.split('.') as [
				keyof typeof draft,
				keyof typeof draft.artwork | undefined
			];

			if (childKey) {
				// 类型守卫：确保 parentKey 对应的是 artwork 对象
				const parentValue = draft[parentKey];
				if (typeof parentValue === 'object' && parentValue !== null && childKey in parentValue) {
					(parentValue as Record<string, string>)[childKey] = value;
				}
			} else {
				(draft as any)[parentKey] = value;
			}
		});
	};

	return (
		<>
			<label>
				Name:
				<input value={person.name} name='name' onChange={handleChange}/>
			</label>
			<label>
				Title:
				<input value={person.artwork.title} name="artwork.title" onChange={handleChange}/>
			</label>
			<label>
				City:
				<input value={person.artwork.city} name="artwork.city" onChange={handleChange}/>
			</label>
			<label>
				Image:
				<input value={person.artwork.image} name="artwork.image" onChange={handleChange}/>
			</label>
			<p>
				<i>{person.artwork.title}</i> { ' by ' } {person.name}<br/>
				(located in {person.artwork.city})
			</p>
			<div>
				Img src: {person.artwork.image} <br/>
				Img alt: {person.artwork.title}
			</div>

		</>
	);
};


export default FormObj;